#include "ds_1wire.h"
#include <avr/io.h>
#include <util/delay.h>



Int8U temperature[2];

void delay_us(int us)
{
	//#ifdef ATMEGA16 
	_delay_us(us);
	//#endif
	//#ifdef LPC1766
	//delay();
	//#endif
}

//return 1 if presence
Int8U ds_1wire_reset(void)
{
  Int8U response;
  PIN_DIR_OUTPUT();//master output mode
  PIN_SET_LOW();//pull down DATA line 
  delay_us(500);//for 500us
  PIN_DIR_INPUT();//master release bus
  
  delay_us(60); //60
  response = (THERM_PIN&(1<<THERM_DQ));
  delay_us(420);
  return response;
}

void ds_1wire_write(Int8U byte)
{
	Int8U i=0;
    
	for(i=0;i<8;i++){
	 PIN_SET_LOW();//pull down DATA line
	PIN_DIR_OUTPUT();//master output mode
	_delay_us(1);
		if(byte&1){ //write 1
		    PIN_DIR_INPUT();//master release bus
		_delay_us(60);
		}
		else {	//write 0
			 PIN_SET_LOW();//pull down DATA line
			PIN_DIR_OUTPUT();//master output mode		
			_delay_us(60);
			    PIN_DIR_INPUT();//master release bus;
			}
	byte>>=1;
	}

     
}

Int8U ds_1wire_read(void)
{
   unsigned char k=0;
	unsigned char j=0;
	
	for(j=0;j<8;j++){
	
	PIN_SET_LOW();//pull down DATA line
	PIN_DIR_OUTPUT();//master output mode		
	_delay_us(1);
	PIN_DIR_INPUT();//master release bus;
	_delay_us(10);//15us
	
	if(PIN_READ()) k|=(1<<7);
	if(j!=7)k>>=1;
	_delay_us(40);
	}
	
	return k;

   
}
void ds_1wire_readtemp(void)
{
ds_1wire_reset();
 
 ds_1wire_write(SKIP_ROM);

 ds_1wire_write(CONVERT_T);
  
 
 //while(ds_1wire_readbit());
 _delay_ms(5);
 
 ds_1wire_reset();
 ds_1wire_write(SKIP_ROM);
 ds_1wire_write(READ_SCRATCHPAD);
 temperature[0]=ds_1wire_read();
 PORTC = temperature[0];
 temperature[1]=ds_1wire_read();
 //#ifdef ATMEGA_16
 
 PORTD = temperature[1];
 //#endif
 ds_1wire_reset();    
}